<?php

class Application_Form_ChangePassword extends Zend_Form {

    public function init() {


        $oldpassword = new Zend_Form_Element_Password('oldpassword', array(
                    'label' => 'Aktualne hasło'
                ));
        $oldpassword->setRequired(true);
        $password = new Zend_Form_Element_Password('password', array(
                    'label' => 'Nowe Hasło'
                ));
        $password->addValidator('identical', false, array('repassword', 'Podaj takie samo hasło'));
        $password->setRequired(true);

        $repassword = new Zend_Form_Element_Password('repassword', array(
                    'label' => 'Powtórz nowe'
                ));



        $this->addDisplayGroup(array(
            $oldpassword, $password, $repassword
                ), 'gr-main');
        $submit = new Zend_Form_Element_Submit('submitPassword', array(
                    'label' => 'Zapisz',
            'class' => 'ui-form-button'
                ));

        $this->addDisplayGroup(array(
            $submit
                ), 'gr-submit', array(
            'order' => 999
        ));
    }

    public function isValid($data) {
        $r = parent::isValid($data);

        $auth = Zend_Auth::getInstance();
        $ob = $auth->getStorage()->read();

        $users = new Application_Model_Users();
        $user = $users->getById($ob->id);

        if (preg_match('#^' . md5(Zend_Registry::get('staticSalt') . $data['oldpassword']) . '$#', $user->password) == 0) {
            $this->oldpassword->setErrors(array(
                'Podaj hasło'
            ));
            $r = false;
        }

        return $r;
    }

}